import { useState, useCallback, useEffect } from 'react';
import type { Message, ChatSession, Model } from '../types/chat';
import { chatApi } from '../services/api';

export function useChat() {
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [models, setModels] = useState<Model[]>([]);
  const [selectedModel, setSelectedModel] = useState<string>('');
  const [isLoading, setIsLoading] = useState(false);

  // 加载模型列表
  useEffect(() => {
    chatApi.getModels().then((modelList) => {
      setModels(modelList);
      if (modelList.length > 0 && !selectedModel) {
        setSelectedModel(modelList[0].id);
      }
    });
  }, []);

  // 从数据库加载会话
  useEffect(() => {
    chatApi.getSessions().then((sessionsList) => {
      setSessions(sessionsList);
      if (sessionsList.length > 0) {
        // 尝试从 localStorage 恢复上次查看的会话
        const savedSessionId = localStorage.getItem('currentSessionId');
        let sessionToLoad = sessionsList[0]; // 默认加载最新的会话

        // 如果保存的会话 ID 存在且有效，加载该会话
        if (savedSessionId) {
          const savedSession = sessionsList.find((s) => s.id === savedSessionId);
          if (savedSession) {
            sessionToLoad = savedSession;
          }
        }

        // 加载选中的会话
        chatApi.getSession(sessionToLoad.id).then((session) => {
          if (session) {
            setCurrentSessionId(session.id);
            setMessages(session.messages);
            setSelectedModel(session.model);
            // 保存当前会话 ID 到 localStorage
            localStorage.setItem('currentSessionId', session.id);
          }
        });
      }
    });
  }, []);

  // 创建新会话
  const createNewSession = useCallback(async () => {
    try {
      const model = selectedModel || models[0]?.id || '';
      const newSession = await chatApi.createSession(model);
      setCurrentSessionId(newSession.id);
      setMessages([]);
      setSessions([newSession, ...sessions]);
      // 保存新会话 ID 到 localStorage
      localStorage.setItem('currentSessionId', newSession.id);
    } catch (error) {
      console.error('Error creating session:', error);
    }
  }, [sessions, selectedModel, models]);

  // 选择会话
  const selectSession = useCallback(
    async (sessionId: string) => {
      try {
        const session = await chatApi.getSession(sessionId);
        if (session) {
          setCurrentSessionId(sessionId);
          setMessages(session.messages);
          setSelectedModel(session.model);
          // 保存当前会话 ID 到 localStorage
          localStorage.setItem('currentSessionId', sessionId);
        }
      } catch (error) {
        console.error('Error loading session:', error);
      }
    },
    []
  );

  // 删除会话
  const deleteSession = useCallback(
    async (sessionId: string) => {
      try {
        const success = await chatApi.deleteSession(sessionId);
        if (success) {
          const newSessions = sessions.filter((s) => s.id !== sessionId);
          setSessions(newSessions);
          if (currentSessionId === sessionId) {
            if (newSessions.length > 0) {
              await selectSession(newSessions[0].id);
            } else {
              setCurrentSessionId(null);
              setMessages([]);
              // 清除 localStorage 中的会话 ID
              localStorage.removeItem('currentSessionId');
            }
          }
        }
      } catch (error) {
        console.error('Error deleting session:', error);
      }
    },
    [sessions, currentSessionId, selectSession]
  );

  // 发送消息（流式）
  const sendMessage = useCallback(
    async (content: string) => {
      let sessionId = currentSessionId;
      let currentMessages = messages;

      // 如果没有当前会话，创建新会话
      if (!sessionId) {
        try {
          const model = selectedModel || models[0]?.id || '';
          const newSession = await chatApi.createSession(model);
          sessionId = newSession.id;
          currentMessages = [];
          setCurrentSessionId(sessionId);
          setMessages([]);
          setSessions([newSession, ...sessions]);
          // 保存新会话 ID 到 localStorage
          localStorage.setItem('currentSessionId', sessionId);
        } catch (error) {
          console.error('Error creating session:', error);
          return;
        }
      }

      const userMessage: Message = {
        id: Date.now().toString(),
        role: 'user',
        content,
        timestamp: new Date(),
      };

      const newMessages = [...currentMessages, userMessage];
      setMessages(newMessages);
      setIsLoading(true);

      // 创建 AI 消息占位符
      const assistantMessageId = (Date.now() + 1).toString();
      const assistantMessage: Message = {
        id: assistantMessageId,
        role: 'assistant',
        content: '',
        timestamp: new Date(),
      };

      const messagesWithPlaceholder = [...newMessages, assistantMessage];
      setMessages(messagesWithPlaceholder);

      try {
        let accumulatedContent = '';

        await chatApi.sendMessageStream(
          content,
          selectedModel || models[0]?.id || '',
          sessionId,
          (chunk: string) => {
            // 实时更新消息内容
            accumulatedContent += chunk;
            setMessages((prevMessages) => {
              const updated = [...prevMessages];
              const lastMessage = updated[updated.length - 1];
              if (lastMessage && lastMessage.id === assistantMessageId) {
                lastMessage.content = accumulatedContent;
              }
              return updated;
            });
          },
          (newSessionId: string) => {
            // 更新会话 ID
            if (newSessionId !== sessionId) {
              sessionId = newSessionId;
              setCurrentSessionId(newSessionId);
              // 保存会话 ID 到 localStorage
              localStorage.setItem('currentSessionId', newSessionId);
            }
          },
        );

        // 刷新会话列表
        const updatedSessions = await chatApi.getSessions();
        setSessions(updatedSessions);
      } catch (error) {
        console.error('Error sending message:', error);
        const errorMessage: Message = {
          id: assistantMessageId,
          role: 'assistant',
          content: error instanceof Error ? error.message : '发送消息失败，请稍后重试',
          timestamp: new Date(),
        };
        setMessages((prevMessages) => {
          const updated = [...prevMessages];
          updated[updated.length - 1] = errorMessage;
          return updated;
        });
      } finally {
        setIsLoading(false);
      }
    },
    [messages, selectedModel, currentSessionId, sessions, models]
  );

  // 切换模型
  const changeModel = useCallback(
    (modelId: string) => {
      setSelectedModel(modelId);
      // 模型切换后，如果需要更新会话，可以在这里处理
    },
    []
  );

  return {
    sessions,
    currentSessionId,
    messages,
    models,
    selectedModel,
    isLoading,
    sendMessage,
    changeModel,
    createNewSession,
    selectSession,
    deleteSession,
  };
}

